package com.ruoyi.system.service.impl;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IFactorCategoryService;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.UserFactorItemMapper;
import com.ruoyi.system.service.IUserFactorItemService;

/**
 * 自定义因子Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-01-26
 */
@Service
public class UserFactorItemServiceImpl implements IUserFactorItemService 
{
    @Autowired
    private UserFactorItemMapper userFactorItemMapper;
    @Autowired
    private IFactorCategoryService factorCategoryService;


    /**
     * 查询自定义因子
     * 
     * @param factorItemId 自定义因子主键
     * @return 自定义因子
     */
    @Override
    public UserFactorItemOp selectUserFactorItemByFactorItemId(String factorItemId) {
        UserFactorItem userFactorItem = userFactorItemMapper.selectUserFactorItemByFactorItemId(factorItemId);
        UserFactorItemOp userFactorItemOp = new UserFactorItemOp();
        userFactorItemOp.setStrategyNm(userFactorItem.getFactorItemTitle());
        userFactorItemOp.setFactorItemEng(userFactorItem.getFactorItemEng());
        userFactorItemOp.setLongText(userFactorItem.getLongText());
        userFactorItemOp.setFactorItemId(userFactorItem.getFactorItemId());
        return userFactorItemOp;
    }

    /**
     * 查询自定义因子列表
     * 
     * @param userFactorItem 自定义因子
     * @return 自定义因子
     */
    @Override
    public List<UserFactorItem> selectUserFactorItemList(UserFactorItem userFactorItem)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(!user.getUserId().toString().equals("1")){
            userFactorItem.setUserId(user.getUserId().toString());
        }

        return userFactorItemMapper.selectUserFactorItemList(userFactorItem);
    }

    /**
     * 新增自定义因子
     * 
     * @param userFactorItemOp 自定义因子
     * @return 结果
     */
    @Override
    public String insertUserFactorItem(UserFactorItemOp userFactorItemOp)
    {
        try{
            SysUser user = SecurityUtils.getLoginUser().getUser();
            int count=userFactorItemMapper.finduserFactorItemEng(userFactorItemOp.getFactorItemEng(),user.getUserId().toString());
            if(count>0)
                return "因子的英文名称已经存在";
            String s = factorCategoryService.finduserlongTextUsed(userFactorItemOp.getLongText());
            if(!s.equals("验证成功"))
                return s;

            UserFactorItem userFactorItem = new UserFactorItem();
            //先赋值
            userFactorItem.setFactorItemId(IdUtils.fastSimpleUUID());
            userFactorItem.setFactorItemTitle(userFactorItemOp.getStrategyNm());
            userFactorItem.setParentCategoryId("9000");
            userFactorItem.setParentCategoryTitle("自定义因子");
            userFactorItem.setUserId(user.getUserId().toString());
            userFactorItem.setUpdateTime(new Date());
            userFactorItem.setLongText(userFactorItemOp.getLongText());
            userFactorItem.setFactorItemEng(userFactorItemOp.getFactorItemEng());
    //        userFactorItem.setXmlText(testAddItem(userFactorItemOp));
            userFactorItemMapper.insertUserFactorItem(userFactorItem);
            return "新增成功";
        }catch (Exception e){
            e.printStackTrace();
        }
        return "新增失败";
    }

    /**
     * 修改自定义因子
     * 
     * @param userFactorItemOp 自定义因子
     * @return 结果
     */
    @Override
    public String updateUserFactorItem(UserFactorItemOp userFactorItemOp)
    {
        try{
        SysUser user = SecurityUtils.getLoginUser().getUser();
        int count=userFactorItemMapper.finduserFactorItemEng(userFactorItemOp.getFactorItemEng(),user.getUserId().toString());
        if(count>0)
            return "因子的英文名称已经存在";
        String s = factorCategoryService.finduserlongTextUsed(userFactorItemOp.getLongText());
        if(!s.equals("验证成功"))
            return s;

        UserFactorItem userFactorItem = new UserFactorItem();
        //先赋值
        userFactorItem.setFactorItemId(userFactorItemOp.getFactorItemId());
        userFactorItem.setFactorItemTitle(userFactorItemOp.getStrategyNm());
        userFactorItem.setUpdateTime(DateUtils.getNowDate());
        userFactorItem.setLongText(userFactorItemOp.getLongText());
        userFactorItem.setFactorItemEng(userFactorItemOp.getFactorItemEng());
        //        userFactorItem.setXmlText(testAddItem(userFactorItemOp));
        userFactorItemMapper.updateUserFactorItem(userFactorItem);
        return "修改成功";
        }catch (Exception e){
        e.printStackTrace();
        }
        return "修改失败";
    }

    /**
     * 批量删除自定义因子
     * 
     * @param factorItemIds 需要删除的自定义因子主键
     * @return 结果
     */
    @Override
    public int deleteUserFactorItemByFactorItemIds(String[] factorItemIds)
    {
        return userFactorItemMapper.deleteUserFactorItemByFactorItemIds(factorItemIds);
    }

    /**
     * 删除自定义因子信息
     * 
     * @param factorItemId 自定义因子主键
     * @return 结果
     */
    @Override
    public int deleteUserFactorItemByFactorItemId(String factorItemId)
    {
        return userFactorItemMapper.deleteUserFactorItemByFactorItemId(factorItemId);
    }

    /**
     * 将前段数据转化成xml字符串
     * @param userFactorItemOp
     * @return
     */
    private ArrayList<Item> getItemList(UserFactorItemOp userFactorItemOp){
        ArrayList<Item> items=new ArrayList<>();
        if(userFactorItemOp.getLongText3()!=null){
            Item item = new Item();
            item.setId(IdUtils.fastSimpleUUID());
            item.setName(userFactorItemOp.getFactorItemTitle());
            item.setOp(userFactorItemOp.getPostIds2());
            String params = userFactorItemOp.getLongText3().split("\\(")[1].split("\\)")[0];
            item.setParams("{"+params+"}");
            items.add(item);
            return items;
        }else if(userFactorItemOp.getLongText()!=null){
            return this.getItemsByNewdatas(userFactorItemOp.getLongText());
        }
        else {
            Item item = new Item();
            item.setId(IdUtils.fastSimpleUUID());
            item.setName(userFactorItemOp.getFactorItemTitle());
            item.setOp(userFactorItemOp.getPostIds1());
            String params1 = userFactorItemOp.getLongText1().split("\\(")[1].split("\\)")[0];
            String params2 = userFactorItemOp.getLongText2().split("\\(")[1].split("\\)")[0];
            item.setParams("{"+params1+"}"+","+"{"+params2+"}");
            items.add(item);
            return items;
        }

    }

    /**
     * 增加：自定义文档的属性
     */
    public String testAddItem(UserFactorItemOp userFactorItemOp) throws DocumentException, IOException {
        //1.创建文档
        Document doc=DocumentHelper.createDocument();
        //2.添加标签
        Element rootElem=doc.addElement("CombineFactorList");
        ArrayList<Item> items = this.getItemList(userFactorItemOp);
        for(Item item:items){
            //4.增加Factor属性
            Element stuElem=rootElem.addElement("Factor");
            stuElem.addAttribute("id", item.getId());
            stuElem.addAttribute("name", item.getName());
            //4.增加Item属性
            for(ItemChild itemChild :item.getItemChildren()){
                Element Item = stuElem.addElement("Item");
                Item.addAttribute("seq",itemChild.getSeq());
                Item.addAttribute("id",itemChild.getId());
                Item.addAttribute("type",itemChild.getType());
                Item.addAttribute("s_dt",itemChild.getS_dt());
                Item.addAttribute("e_dt",itemChild.getE_dt());
            }
            Element combineAlgr = stuElem.addElement("CombineAlgr");
            combineAlgr.addAttribute("op",item.getOp());
            combineAlgr.addAttribute("params",item.getParams());
        }

        return doc.asXML();
    }

    /**
     * 将字符串转化为item
     * 解析 模仿 C=(TR20(1)+5)*每股归母自由现金流(700009)(1)
     *
     *T1: add=TR20[2],tr30[1];
     * T2: mult=T1[1],每股盈余公积金(700008)[1]
     */

    public  ArrayList<Item> getItemsByNewdatas(String obj){
//        String obj="T1=add:每股股息(700011)[2],每股归母自由现金流(700009)[1],每股归母自由现金流(700009)[1];T2=mult:T1[1],5";
        String[] split = obj.split(";");
        ArrayList<tmpWdmcontroter> tmpWdmcontroters = new ArrayList<>();
        for(String s:split){
            tmpWdmcontroter tmpWdmcontroter = new tmpWdmcontroter();
            String[] split1 = s.split("=");
            tmpWdmcontroter.setName(split1[0]);
            tmpWdmcontroter.setValue(split1[1]);
            tmpWdmcontroters.add(tmpWdmcontroter);
        }
        //将tmpWdmcontroters转换为ArrayList<Item>
        ArrayList<Item> items = new ArrayList<>();
        //定义一个map把name和id放进去
//        ArrayList<Map<String,String>> tmpFactor = new ArrayList<>();
        Map<String,String> tmpFactor=new HashMap<>();
        for(tmpWdmcontroter tmpWdmcontroter:tmpWdmcontroters){

            Item item = new Item();
            String uuid = IdUtils.fastSimpleUUID();
            item.setName(uuid);
            item.setName1(tmpWdmcontroter.getName());
            item.setId(uuid);
            ArrayList<ItemChild> itemChildren = new ArrayList<>();
            String[] split1 = tmpWdmcontroter.getValue().split(",");
            StringBuilder params = new StringBuilder();
            //给UUid赋值给数据
            tmpFactor.put(tmpWdmcontroter.getName(),uuid);

            int i=0;
            for (String s:split1){
                i++;
                ItemChild itemChild=new ItemChild();
                //提取小括号
                List<String> xkh = IdUtils.extractMessageByRegular(s, "\\(([^}]*)\\)");
                //提取中括号
                List<String> zkh = IdUtils.extractMessageByRegular(s,"(\\[[^\\]]*\\])");
                if(xkh.isEmpty()){
                    if (zkh.isEmpty()){
                        if(i!=split1.length){
                            params.append(s).append(",");
                        }else {params.append(s);}
                        continue;
                    } else {
                        //找list中指定的元素
                        String T = IdUtils.extractMessageByRegular(s, "(\\:[^\\]]*\\[)").get(0);

                        itemChild.setId(tmpFactor.get(T));
                        if(i!=split1.length){
                            params.append("{").append(i).append("}").append(",");
                        }else {params.append("{").append(i).append("}");}
                        itemChild.setType("C");
                        String[] split2 = zkh.get(0).split("-");
                        if (split2.length==2){
                            itemChild.setS_dt(split2[0]);
                            itemChild.setE_dt(split2[1]);
                        }else {
                            itemChild.setS_dt(zkh.get(0));
                            itemChild.setE_dt(zkh.get(0));
                        }
                        itemChild.setSeq(String.valueOf(i));
                    }
                }else {
                    itemChild.setId(xkh.get(0));
                    itemChild.setType("F");
                    String[] split2 = zkh.get(0).split("-");
                    if (split2.length==2){
                        itemChild.setS_dt(split2[0]);
                        itemChild.setE_dt(split2[1]);
                    }else {
                        itemChild.setS_dt(zkh.get(0));
                        itemChild.setE_dt(zkh.get(0));
                    }
                    itemChild.setSeq(String.valueOf(i));
                    if(i!=split1.length){
                        params.append("{").append(i).append("}").append(",");
                    }else {
                        params.append("{").append(i).append("}");
                    }

                }
                itemChildren.add(itemChild);

            }

            item.setOp(tmpWdmcontroter.getValue().substring(0,tmpWdmcontroter.getValue().indexOf(":")));
            item.setParams(params.toString());
            item.setItemChildren(itemChildren);
            items.add(item);

        }
        System.out.println(items);
        return items;
    }
}
